/**
 * @date     2018-11-07
 * @author   尹学江
 */
import axios from 'axios';
import {getStore} from './storage';
import {Alert} from 'react-native';
// api 的 base_url
const baseURL = 'http://teamwork.hsdj.top';

// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 60 * 1000,
  headers: {'Content-Type': 'application/json'},
});

// request 拦截器
service.interceptors.request.use(
  async config => {
    const storeToken = await getStore('token');
    config.headers.token = storeToken || '';
    return config;
  },
  error => {
    Alert.alert('提示', '接口出错了');
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  },
);

// response 拦截器
service.interceptors.response.use(
  async response => {
    let res = response.data;
    return res;
  },
  error => {
    console.log('err' + error); // for debug
    return Promise.reject(error);
  },
);

/**
 * 发送ajax请求
 * @param    {String}  url     地址
 * @param    {String}  method  请求方式 get post put delete
 * @param    {Object}  data    参数对象
 * @param    {Object}  ctx 参数
 */
const callApi = (url, method, data, ctx) => {
  if (process.env.NODE_ENV === 'development') {
    // 开发环境
    if (url.indexOf('?') > -1) {
      url += '&t=' + Math.random();
    } else {
      url += '?t=' + Math.random();
    }
  }
  return service(
    Object.assign(
      {},
      {
        url: `${url}`,
        method,
        params: method === 'get' ? data : {},
        data: method !== 'get' ? data : {},
        withCredentials: false,
      },
      ctx,
    ),
  );
};

/**
 * 请求接口
 * @param url 接口地址
 * @param data 接口参数
 * @param ctx 所有请求参数
 */
export const getApi = (url, data = {}, ctx = {}) =>
  callApi(url, 'get', data, ctx);
export const postApi = (url, data = {}, ctx = {}) =>
  callApi(url, 'post', data, ctx);
